#include "common.h"

#include "timer.h"
#include "UART.h"
#include "LcdFunction.h"
#include "ExternalInterrupt.h"

#define BarcodeReceiveComplete (first_data_flag==0 && TCNT0>200)
#define WifiReceiveComplete		 (s_flag && e_flag)

char* ReceivePriceFrWifi(const char*);
char* ReceiveBarcode(const char*);
void PrintAmount_and_Price_on_LCD(const char* strPrice,const char*strAmount);

int main(void){

  char strPrice[8] = {'0','\0'};
  char strAmount[8] = {'0','\0'};
	char barcodeBuffer[16] = {'\0'};
  int amount=0;
  char* LCDstr[8];
  int i=0;
  int lcdprintcount=0;


  InitLCD();

  DDRE = 0b11111110;
  PORTE = 0;

  DDRD = 0b11111011;
  PORTD = 0;
 
  UART0_first_init();
  fdevopen(UART0_putchar, UART0_getchar,0);
  UART1_first_init();
  timer0_initialize();

  sei();

  _delay_ms(1000);

  set_wifimodule();


  while(1){

		 
		if(BarcodeReceiveComplete){
			if( ReceiveBarcode(barcodeBuffer) != 0){
				send_message(barcodeBuffer);
			} 
			first_data_flag = 1;
		}

		if(TCNT0==100){
			if(lcdprintcount++ > 100){
				lcdprintcount = 0;
				PrintAmount_and_Price_on_LCD(strPrice,strAmount);
	  	}
  	}



		if(WifiReceiveComplete){
			s_flag = e_flag =0;
			amount += atoi(ReceivePriceFrWifi(strPrice) );
			itoa(amount,strAmount,10);
		}

	}

  return 0;
}

char* ReceiveBarcode(const char* str)
{
	char* tmpstr = str;
	while(r_in0 != r_out0){
		*tmpstr++ = (unsigned char)UART0_getchar(NULL);
	} *tmpstr = '\0';
	if(*str == '\0')  return 0;
	return str;
}

char* ReceivePriceFrWifi(const char* strPrice)
{
	cli();
	char* tmpstr = strPrice;
	while(r_in1 != r_out1){
		*tmpstr++ = (char)UART1_getchar();
	}
	*tmpstr = '\0';  
	sei();
	
	return strPrice;

}

void PrintAmount_and_Price_on_LCD(const char* strPrice,const char*strAmount)
{
	
	ClearDisp();
	SetLCDAddress(0x03);
	WriteChar(' ');
	WriteStr(strPrice); //if(i>7) i=0;
	WriteStr("Won");
	_delay_ms(3);

	SetLCDAddress(0x28);
	WriteStr(strAmount);
	WriteStr("Won");
	_delay_ms(50);

}
